package com.google.jguery.client;

import java.util.Set;

import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.ExportPackage;
import org.timepedia.exporter.client.Exportable;
import org.timepedia.exporter.client.NoExport;

import com.google.gwt.dom.client.Element;
import com.google.jguery.client.analyzer.Analyzer;
import com.google.jguery.client.analyzer.StandardAnalyzer;
import com.google.jguery.client.index.Index;
import com.google.jguery.client.index.Table;
import com.google.jguery.client.query.And;
import com.google.jguery.client.query.Searcher;

import static com.google.gwt.query.client.GQuery.$;

@Export
@ExportPackage("jGuery")
public class jGuery implements Exportable {
	Table termTable;
	Index index;
	And query;
	Analyzer analyzer;
	Searcher searcher;
	Element [] elements;
	
	public jGuery() {
		termTable = new Table();		
		index = new Index(termTable);
		query = new And();
		analyzer = new StandardAnalyzer();
		searcher = new Searcher(index);
	}
	
	public void clearIndex() {
		termTable.clear();
	}
	
	public int [] getMatchedIds(String words) {
		query.setQueries(words, analyzer);
		Set<Integer> ids = query.getDocIds(searcher);
		if (ids == null || ids.size() == 0) return null;
		int [] matched = new int[ids.size()];
		int i = 0;
		for (int id : ids) {
			matched[i] = id;
			i++;
		}
		return matched;
	}	
	
	public void updateIndexByTag(String tagName) {		
		updateIndex($(tagName).elements());
	}	

	public void updateIndex(Element [] eles) {
		this.elements = eles;
		for (int i=0; i<eles.length; i++) {
			termTable.update(i, eles[i].getInnerText(), analyzer);
		}
		//TODO think a better way how to set the total number of documents/records
		searcher.setDocCountAll(eles.length);
	}
	
	@NoExport
	public Element [] search(String words) {
		query.setQueries(words, analyzer);
		Set<Integer> ids = query.getDocIds(searcher);
		if (ids == null || ids.size() == 0) return null;
		Element [] matched = new Element[ids.size()];
		int i = 0;
		for (int id : ids) {
			matched[i] = elements[id];
			i++;
		}
		return matched;
	}
}